package com.example.webproject.handle;

import com.example.webproject.exception.BusinessException;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hhs
 * @Description 自定义拦截异常页面
 * @date 2022/12/07 20:34
 */
//@ControllerAdvic主要用来处理全局数据
@ControllerAdvice
public class PracticeExceptionHandler {
    @ExceptionHandler(BusinessException.class)
    public ModelAndView businessExceptionHandler(HttpServletRequest request, BusinessException e){
        String errInfo = "业务异常：" + e.getErrInfo();
        ModelAndView mv = new ModelAndView();
        mv.addObject("title", errInfo);
        mv.addObject("url", request.getRequestURL().toString());
        mv.addObject("exception", e);
        mv.setViewName("error/error");
        return mv;
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) throws Exception {

//        如果有些异常标识了自己的HttpStatus状态码就让Spring自己处理（根据状态码找到对应的页面如404）
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
            throw e;
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("title", "非业务异常");
        mv.addObject("url", request.getRequestURL().toString());
        mv.addObject("exception", e);
        mv.setViewName("error/error");
        return mv;
    }
}
